package com.iflytek.esb.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

public class AuthenticationFilter implements Filter {
	
	public static final String LOGIN_ACCOUNT_SESSION_KEY = "__esb_login_account_123098";
	public static final String LOGIN_URL = "/login";
	
	public static ThreadLocal<String> accountThreadLocal = new ThreadLocal<String>();
	
	public static String getLoginAccount() {
		return accountThreadLocal.get();
	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		
		HttpSession session = httpRequest.getSession(); 
		Object account = session.getAttribute(LOGIN_ACCOUNT_SESSION_KEY);
		
		if (account == null) {
			String loginUrl = combineUrl(httpRequest.getContextPath(), LOGIN_URL);
			httpResponse.sendRedirect(loginUrl);
			return;
		}
		
		accountThreadLocal.set(String.valueOf(account));
		chain.doFilter(request, response);
	}

	public void destroy() {
	}

	private String combineUrl(String part1, String part2) {
		final String SLASH = "/";
		String p1 = part1;
		String p2 = part2;
		
		if (!StringUtils.startsWith(p1, SLASH)) {
			p1 = SLASH + p1;
		}
		
		if (StringUtils.startsWith(p2, SLASH)) {
			p2 = StringUtils.substring(p2, 1);
		}
		
		if (StringUtils.equals(p1, SLASH)) {
			return SLASH + p2;
		}
		else {
			return p1 + SLASH + p2;
		}
	}

}
